//
//  MTRedPacketListController.swift
//  MT
//
//  Created by 陈悦 on 2020/5/8.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory
import YPNavigationBarTransition
import RxSwift
import RxCocoa
import Moya
import Result

class MTRedPacketListController: BaseViewController {
    
    var isSend: Bool = false {
        didSet {
            title = isSend ? "我送出的红包" : "我收到的红包"
        }
    }
    /// MineApi
    private lazy var provider: MTProvider<MineApi> = {
        let provider = MTProvider<MineApi>(plugins: [MTLoadingDataPlugin.init(viewController: self)])
        return provider
    }()
    
    private let disposeBag = DisposeBag()
    private var result: [MTRedPacketReportSubModel] = []
    private var currentPage: Int = 1
    private let pageSize: Int = 20
    lazy var tableView: UITableView = {
        let table = UITableView(frame: self.view.bounds, style: .grouped)
        table.delegate = self
        table.dataSource = self
        table.register(RedPacketListCell.self, forCellReuseIdentifier: RedPacketListCell.reuseIdentity())
        table.separatorInset = UIEdgeInsets.zero
        table.tableFooterView = UIView()
        table.mj_footer = ViewFactory.normalFooter(target: self, selector: #selector(loadMore))
        table.mj_header = ViewFactory.normalHeader(target: self, selector: #selector(loadFirst))
        table.backgroundColor = UIColor.theme.background
        table.emptySetView = ViewFactory.emptySetView { [weak self] in

            guard let weakSelf = self else { return }

            weakSelf.loadFirst()

        }
        return table
    }()
    
    lazy var blackBack: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex:0x2f2f2f)
        return view
    }()
    
    lazy var titleLab: UILabel = {
        let lab = UILabel()
        lab.text = "一共送出钻石"
        lab.font = PingFangSCMediumFont(12)
        lab.textColor = UIColor(hex:0x9b9b9b)
        lab.textAlignment = .center
        return lab
    }()
    
    lazy var icon: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "dimond")
        return imageView
    }()
    
    lazy var amountLabel: UILabel = {
        let l = UILabel()
        l.textColor = .white
        l.font = PingFangSCSemiboldFont(20)
        l.textAlignment = .right
        return l
    }()
    
    override func refreshView() {
        loadFirst()
    }
    
    private func loadData(loadMore: Bool) {
        provider.rx.requestResult(isSend ? .redPacketSendList(currentPage) : .redPacketReceiveList(currentPage)).subscribe(onNext: { [weak self] (result:Result<MTRedPacketReportModel, AnyError> , isCache:Bool) in
            guard let weakSelf = self else { return }
            switch result {
            case .success(let model):
                if model.code == 200 {
                    weakSelf.amountLabel.text = "\(model.giftSum ?? 0)"
                    weakSelf.tableView.mj_footer?.endRefreshing()
                    weakSelf.tableView.mj_header?.endRefreshing()
                    if weakSelf.currentPage == 1 {
                        weakSelf.tableView.mj_footer?.state = .idle
                    }
                    
                    if let r = model.result {
                        if (model.page?.pages == weakSelf.currentPage) {
                            weakSelf.tableView.mj_footer?.endRefreshingWithNoMoreData()
                        }
                        if loadMore == true {
                            weakSelf.result = weakSelf.result + r
                        } else {
                            weakSelf.result = r
                        }
                        
                        weakSelf.hiddenHF(isHidden: weakSelf.result.count == 0)
                    } else {
                        weakSelf.hiddenHF(isHidden: true)
                    }
                    
                    DispatchQueue.main.async {
                        weakSelf.tableView.reloadData()
                    }
                }
                break
            case .failure( _):
                
                break
            }
            
        }).disposed(by: globalDisposedBag)
    }
    
    @objc private func hiddenHF(isHidden: Bool) {
        self.tableView.mj_header?.isHidden = isHidden
        self.tableView.mj_footer?.isHidden = isHidden
    }
    
    @objc private func loadFirst() {
        self.currentPage = 1
        
        loadData(loadMore: false)
    }
    
    @objc private func loadMore() {
        
        self.currentPage = self.currentPage + 1
        
        loadData(loadMore: true)
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(tableView)
        
        if isSend {
            let header = headerView()
            view.addSubview(header)
            header.snp.makeConstraints { (make) in
                make.left.right.equalToSuperview()
                make.top.equalToSuperview().offset(NavigationBarHeight+StatusBarHeight)
                make.height.equalTo(90)
            }
            
            tableView.snp.makeConstraints { (make) in
                make.edges.equalToSuperview().inset(UIEdgeInsets(top: 90+NavigationBarHeight+StatusBarHeight, left: 0, bottom: 50, right: 0))
            }
        } else {
            tableView.snp.makeConstraints { (make) in
                make.edges.equalTo(view)
            }
        }
        
        loadFirst()
    }
}

extension MTRedPacketListController {
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .default
    }
}

extension MTRedPacketListController {
    private func headerView() -> UIView {
        blackBack.addSubview(titleLab)
        blackBack.addSubview(icon)
        blackBack.addSubview(amountLabel)
        
        titleLab.snp.makeConstraints { (make) in
            make.centerX.equalTo(blackBack)
            make.top.equalTo(20)
        }
        
        amountLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(titleLab).offset(-8)
            make.top.equalTo(titleLab.snp.bottom).offset(3)
        }
        
        icon.snp.makeConstraints { (make) in
            make.left.equalTo(amountLabel.snp.right).offset(4)
            make.centerY.equalTo(amountLabel)
            make.width.height.equalTo(24)
        }
        return blackBack
    }
}

// MARK: ---------------------------------------- 事件方法 --------------------------------------------
@objc
extension MTRedPacketListController {
    
    private func redPacketListController(didClickContactButton sender: UIButton) {
        
    }
    
    
}

extension MTRedPacketListController: UITableViewDataSource, UITableViewDelegate {
    
    //MARK: UITableViewDataSource
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.result.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: RedPacketListCell.reuseIdentity(), for: indexPath) as! RedPacketListCell
        cell.selectionStyle = .none
        if result.count > indexPath.row {
            cell.model = self.result[indexPath.row]
            cell.isSend = isSend
        }
        return cell
    }
    
    //MARK: UITableViewDelegate
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 64
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
}
